package com.example.anno.ioc.config;

import com.example.anno.entity.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;

@Configuration
@PropertySource(value = {"classpath:/db.properties", "classpath:/env.properties"})
@ComponentScans({
        // mvc.xml
        @ComponentScan(basePackages = {"com.example.anno.ioc"}, useDefaultFilters = false,
                includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})}),
        // applicationContext.xml
        @ComponentScan(basePackages = {"com.example.anno.ioc"}, useDefaultFilters = true,
                excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class})})
})
public class Config01 implements InitializingBean, EnvironmentAware {
    private static final Logger log = LoggerFactory.getLogger(Config01.class);

    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        String profile = environment.getProperty("env.profile");
        String jdbcUrl = environment.getProperty("jdbc.url");
        log.info("env.properties profile: {}", profile);
        log.info("env.properties jdbcUrl: {}", jdbcUrl);
    }

    @Bean
    public FactoryBean<Color> color() {
        // builder
        return new FactoryBean<>() {
            private static final Color instance = new Color();
            @Override
            public Color getObject() throws Exception {
                return instance;
            }

            @Override
            public Class<?> getObjectType() {
                return Color.class;
            }
        };
    }
}
